package us.gaaoc.framework.util.pdf;
/*
 * @authur Frank July 5th, 2007
 */

import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;

public class TiffToPDFConverter {
	public TiffToPDFConverter() {};

	Document document = new Document();
	public String execute(String tiff_file) {
		String pdf_file = tiff_file.substring(0,tiff_file.lastIndexOf('.') + 1) + "pdf";
		try {
			PdfWriter writer = PdfWriter.getInstance(document,
					new FileOutputStream(pdf_file));
			int pages = 0;
			document.open();
			PdfContentByte cb = writer.getDirectContent();
			RandomAccessFileOrArray ra = null;
			int comps = 0;
			try {
				ra = new RandomAccessFileOrArray(tiff_file);
				comps = TiffImage.getNumberOfPages(ra);
			} catch (Throwable e) {
				System.out.println("Exception in " + tiff_file + " "
						+ e.getMessage());
				//continue;
			}
			System.out.println("Processing: " + tiff_file);
			for (int c = 0; c < comps; ++c) {
				try {
					Image img = TiffImage.getTiffImage(ra, c + 1);
					if (img != null) {
						System.out.println("page " + (c + 1));
						if (img.scaledWidth() > 500 || img.scaledHeight() > 700) {
							// if (img.getScaledWidth() > 500 ||
							// img.getScaledHeight() >
							// 700) {
							img.scaleToFit(500, 700);
						}
						img.setAbsolutePosition(20, 20);
						document.add(new Paragraph(tiff_file + " - page "
								+ (c + 1)));
						cb.addImage(img);
						document.newPage();
						++pages;
					}
				} catch (Throwable e) {
					System.out.println("Exception " + tiff_file + " page "
							+ (c + 1) + " " + e.getMessage());
				}
			}
			ra.close();
			document.close();
			//return pdf_file;
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return pdf_file;
	}
}
